const app = getApp()
const utils = require('../../utils/util.js')
Page({
  data: {
    isLoginShow: false, // 是否展示登录
    hasPermission : false, //是否有数据权限
    functionModuleShow : false, //是否展示引导功能区：是否已注册，是否绑定手机号，是否有数据权限
    isRegister : false,//是否已注册
    isShowBind : false, //是否绑定手机号
    hasDataPermission : false, //下面的统计功能区
    normalSum: '-',
    errorSum: '-',
    dataList: [
      // {
      //   name: '水槽',
      //   image: 'http://public.qiniu.hongxiaobin.cn/niushe/icon1.png',
      //   normalSum: 1,
      //   errorSum: 0
      // },
      // {
      //   name: '动物特征',
      //   image: 'http://public.qiniu.hongxiaobin.cn/niushe/icon2.png',
      //   normalSum: 1,
      //   errorSum: 0
      // },
      // {
      //   name: '精准喷淋',
      //   image: 'http://public.qiniu.hongxiaobin.cn/niushe/icon3.png',
      //   normalSum: 1,
      //   errorSum: 0
      // },{
      //   name: '电子秤',
      //   image: 'http://public.qiniu.hongxiaobin.cn/niushe/icon4.png',
      //   normalSum: 1,
      //   errorSum: 0
      // },{
      //   name: '奶厅',
      //   image: 'http://public.qiniu.hongxiaobin.cn/niushe/icon5.png',
      //   normalSum: 1,
      //   errorSum: 0
      // }
      // ,{
      //   name: '其他',
      //   image: 'http://public.qiniu.hongxiaobin.cn/niushe/icon6.png',
      //   normalSum: 1,
      //   errorSum: 0
      // }
    ],
    skin: ''
  },
  
  onLoad: function () {
    let that = this;
    let token = wx.getStorageSync('token') || '';
    if (token) {
      that.loadUser();
    } else {
      utils.promiseLogin().then(function(res){
        if (res.code == 200) { //说明绑定了手机和注册了
          if (!res.data.companyId) {
            that.setHavePermission(true);
          } else {
            that.setHavePermission(false);
            that.setData({
              hasDataPermission : true
            });
            that.getSceneStatistics();
          }
        } else if (res.code == 401) { //用户不存在
          that.setRegister(true);
        } else if (res.code == 402) {//需要绑定手机
          that.setShowBind(true);
        } else if (res.code == 403) {
          that.setHavePermission(true); //没有权限
        } else {
          console.log("其他错误");
        }
      }).catch(function(e){
        console.log(e);
      });
    }

    app.setNavBar()
    const { skin } = app.globalData
    this.setData({
      skin
    })
  },
  handleBindMobile() {
    wx.redirectTo({
      url: '/pages/phone/bind?from=index'
    });
  },
  toPageBarn(event) {
    var that = this;
    console.log(event.currentTarget.dataset);
    var jumpUrl = '/pages/barn/indexSimple?typeId=' + (event.currentTarget.dataset.typeId || 0);
    if (event.currentTarget.dataset.typeId == 3) {
      jumpUrl = '/pages/equipment/basalist';
    } else if (event.currentTarget.dataset.typeId == 4) {
      jumpUrl = '/pages/barn/index?typeId=' + (event.currentTarget.dataset.typeId || 0);
    } else if (event.currentTarget.dataset.typeId == 5) {
      jumpUrl = '/pages/control/index';
    }
    console.log(jumpUrl);
    wx.navigateTo({
      url: jumpUrl
    });
  },

  // 获取用户信息
  getUserInfo(e) {
    // 拒绝授权，返回
    if (!e.detail || !e.detail.userInfo) { 
      return false; 
    }
    this.setData({
      isLogin: true
    })
  },
  getSceneStatistics : function(){
    let that = this;
    utils.promiseGet('/wx/property/sceneStatistics', {'env' : 'dev1'}).then(res => {
      if (res.code == 200) {
        let allStatusCount = res.data && res.data.allStatusCount ? res.data.allStatusCount : {};
        res.data.statusCountList.push({
          actionFunction: "toPageBarn",
          errorSum: 2,
          icon: "https://hlg-zs-material.oss-cn-zhangjiakou.aliyuncs.com/hlg_material/20210411/3215139_165547_6072b9936fa43_4576.png",
          name: "柜子",
          normalSum: 17,
          typeId: 5,
        }); 
        that.setData({
          "normalSum" : allStatusCount.normalSum,
          "errorSum" :  allStatusCount.errorSum,
          "dataList" : res.data.statusCountList || []
        });
      } else {
        wx.showModal({
          title: '提示',
          content: '系统错误，请联系管理员',
          showCancel: false,
          success(res) { }
        });
      }
    }).catch(e => {
      console.log(e);
    });
  },
  toNiunengMuchang : function() {
    wx.navigateToMiniProgram({
      appId: 'wx6a21560db637f52c',
      path: 'pages/index/index',
      extraData: {
      },
      envVersion: 'release',
      success(res) {
          
      }
    });
  },
  loadUser : function(){
    let that = this;
    utils.promiseGet('/wx/user/getAccountInfo', {}).then(function (res) {
      if (res.code == 200) { //说明绑定了手机和注册了
        wx.setStorageSync('userInfo', res.data);
        wx.setStorageSync('token', res.data.token);
        if (!res.data.companyId) {
          that.setHavePermission(true);
        } else {
          that.setHavePermission(false);
          that.setData({
            hasDataPermission : true
          });
          that.getSceneStatistics();
        }
      } else if (res.code == 401) { //用户不存在
        that.setRegister(true);
      } else if (res.code == 402) {//需要绑定手机
        that.setShowBind(true);
      } else if (res.code == 403) {
        that.setHavePermission(true); //没有权限
      } else {
        console.log("其他错误");
      }
    }).catch(function(e){
      console.log(e);
    });
  },
  setRegister : function (isRegisterParam){
    this.setData({
      isRegister: isRegisterParam,
      functionModuleShow : this.data.hasPermission ||  isRegisterParam || this.data.isShowBind
    });
  }, 
  setHavePermission : function(havePermission) {
    this.setData({
      hasPermission: havePermission,
      functionModuleShow : havePermission ||  this.data.isRegister || this.data.isShowBind
    });
  },
  setShowBind : function(bind) {
    this.setData({
      isShowBind: bind,
      functionModuleShow : bind ||  this.data.isRegister || this.data.hasPermission
    });
  },
  handleToRegister : function(){
    this.setData({
      isLoginShow: true
    });
  },
  handleGetUserInfo: function (e) {
    let that = this;
    console.log(e.detail.errMsg)
    console.log(e.detail.userInfo)
    if (e.detail.userInfo) { //说明已经授权，上传数据进行注册
      let eUserInfo = e.detail.userInfo;
      let registerApiParam = {
        "country": eUserInfo.country,
        "province": eUserInfo.province,
        "city": eUserInfo.city,
        "avatar": eUserInfo.avatarUrl,
        "gender": eUserInfo.gender,
        "nickName": eUserInfo.nickName
      }
      utils.wxlogin().then(function (wxloginRes) {
        registerApiParam.code = wxloginRes.code;
        utils.promiseRequest('/wx/user/register', 'POST', registerApiParam).then(res => {
          if (res.code == 200) { //注册成功
            that.setData({
              isLoginShow: false
            });
            that.setRegister(false);
            that.setShowBind(true)
            // app.globalData.tryGetUserUser = true;
            // wx.switchTab({
            //   url: '/pages/index/index',
            // });
            //that.loadUser();
          } else {
            wx.showModal({
              title: '提示',
              content: '注册失败，请联系管理员',
              showCancel: false,
              success(res) { }
            });
          }
        }).catch(e => {
          console.log(e);
        });
      }).catch(function(e){
        console.log(e);
      });
    }
  }
})
